package com.test.simplechat.controller;


import com.test.simplechat.server.MyChannelHandlerPool;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static com.test.simplechat.server.MyChannelHandlerPool.*;

/**
 * 在线人数
 *
 * @author wen
 */
@CrossOrigin
@RequestMapping("/chat")
@Controller
public class OnlineUserController {


    /**
     * 查询用户
     *
     * @return
     */
    @PostMapping("/queryUser")
    @ResponseBody
    public Object queryUser(@RequestBody Map<String, Object> req) {
        String username = (String) req.get("username");
        boolean flag = false;
        try {

            flag = !CHANNEL_ID_MAP.isEmpty() && CHANNEL_ID_MAP.containsKey(username);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return flag;
    }

    /**
     * 在线人数
     *
     * @return
     */
    @GetMapping("/onlineUsers")
    @ResponseBody
    public Object onlineUsers(@RequestParam("selfUsername") String selfUsername) {
        Map<String, List<Object>> onlineUserMap = new ConcurrentHashMap<>();
        Map<String, Object> resultMap = new ConcurrentHashMap<>();
        Set<String> userIndex = new HashSet<>();
        try {
//            if (!CHANNEL_ID_MAP.isEmpty()) {
//                CHANNEL_ID_MAP.keySet().stream().sorted(Comparator.naturalOrder()).forEach(s -> {
//                    String pingyinUserName = ChineseTools.getFirstLetter(s).substring(0, 1);
//                    if (!onlineUserMap.containsKey(pingyinUserName)) {
//                        onlineUserMap.putIfAbsent(pingyinUserName, new ArrayList<>());
//                    }
//                    onlineUserMap.get(pingyinUserName).add(s);
//                });
//                userIndex = onlineUserMap.keySet();
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultMap.put("userIndex", userIndex);
        resultMap.put("userList", onlineUserMap);
        resultMap.put("userCount", CHANNEL_ID_MAP.keySet().size());
        return resultMap;
    }
}
